package io.gitee.tuo_tuo.jfinaldevassistance.db;

import com.jfinal.plugin.activerecord.Model;

import java.util.*;

/**
 * 类名称：外键约束仓库
 * 描述:
 * 版权: Copyright (c) 2018
 * 作者: tuotuo
 * 版本: 1.0
 * 创建日期: 2018/7/31
 * 创建时间: 18:40
 */
public class ForeignKeyRepertory {

	public static Set<ForeignKeyConstraint> repertory = new HashSet<>();

	public static void add(ForeignKeyConstraint constraint){
		repertory.add(constraint);
	}

	public static void add(Class<? extends Model> modelClass, String key,
								 Class<? extends Model> foreignModelClass, String foreignKey, ForeignKeyConstraint.Relation relation){
		add(new ForeignKeyConstraint(modelClass, key, foreignModelClass, foreignKey, relation));
	}

	public static List<ForeignKeyConstraint> get(Class<? extends Model> modelClass, Class<? extends Model> foreignModelClass){
		List<ForeignKeyConstraint> list = new ArrayList<>();
		repertory.forEach( constraint -> {
			if(constraint.modelClass.equals(modelClass) && constraint.foreignModelClass.equals(foreignModelClass)){
				list.add(constraint);
			}else if(constraint.foreignModelClass.equals(modelClass) && constraint.modelClass.equals(foreignModelClass)){
				list.add(constraint);
			}
		});
		return list;
	}

	public static ForeignKeyConstraint getFirst(Class<? extends Model> modelClass, Class<? extends Model> foreignModelClass){
		List<ForeignKeyConstraint> foreignKeyConstraints = get(modelClass, foreignModelClass);
		if(foreignKeyConstraints.size() > 0){
			return foreignKeyConstraints.get(0);
		}
		return null;
	}

}
